<template>
  <view class="header">
    <view class="header__bg" :style="{ background: background }" />
    <view class="header__content">
      <view class="header__content-wrap">
        <skeleton
          animate
          :row="1"
          :loading="loading"
          row-width="210rpx"
          row-height="290rpx"
          row-distance="0"
          bg-color="#eee"
          class="header__content-img"
        >
          <image
            class="header__content-image"
            :src="bookInfo.imgUrl"
            :alt="bookInfo.name"
          />
        </skeleton>
        <skeleton
          title
          :row="4"
          bg-color="#eee"
          :loading="loading"
          class="header__content-detail"
        >
          <view class="header__content-title">{{ bookInfo.name }}</view>
          <view class="header__content-des">别名：{{ bookInfo.alias }}</view>
          <view class="header__content-des">作者：{{ bookInfo.author }}</view>
          <view class="header__content-des">
            类型：{{ bookInfo.classification }}
          </view>
          <view class="header__content-des">状态：{{ status }}</view>
          <view class="header__content-des">更新时间：{{ updateTime }}</view>
          <!-- #ifndef MP-WEIXIN -->
          <!-- <view class="header__content-des">价格：{{ price }}</view> -->
          <!-- #endif -->
        </skeleton>
      </view>
      <!-- 按钮操作 -->
      <view class="header__buttons">
        <button
          class="header__buttons-item"
          v-for="item in buttons"
          :key="item"
          @click="handleButtonClick(item)"
        >
          <text :class="['iconfont', getButtonIcon(item)]"></text>
          <text>{{ getButtonText(item) }}</text>
        </button>
      </view>
      <!-- 分享组件 -->
      <Share
        :show.sync="showShare"
        :options="['wechat', 'poster', 'copy']"
        :copy-text="copyText"
        :poster-url="posterUrl"
        use-close-func
        @close="handleShareClose"
      />
    </view>
  </view>
</template>

<script>
const BUTTONS = {
  readNow: {
    text: '立即阅读',
    func: 'handleReadNow',
    icon: 'icon-yuedu',
  },

  buyNow: {
    text: '解锁书籍',
    func: 'handleBuyNow',
    icon: 'icon-xihuan',
  },

  backToIndex: {
    text: '返回首页',
    func: 'handleBackToIndex',
    icon: 'icon-shouye',
  },

  shareBook: {
    text: '分享一下',
    func: 'handleShareBook',
    icon: 'icon-fenxiang',
  },
};

import Share from '@/components/Share';
import { formatDateToNormalStr, getBookShareUrl } from '@/utils';
import { get } from '@/utils';
import { mapGetters, mapState } from 'vuex';

export default {
  components: {
    Share,
  },

  props: {
    loading: {
      type: Boolean,
      default: true,
    },

    bookInfo: Object,
  },

  data() {
    return {
      buttons: ['readNow', 'shareBook', 'backToIndex'],
      hasAddToList: false,
    };
  },

  computed: {
    ...mapGetters(['shareCode', 'hasLogin', 'userInfo', 'settings', 'autoSecretCode']),
    ...mapState({
      showShare: (state) => state.bookdetail.showShare,
    }),

    // 是否为分享白名单
    isInWhiteList() {
      return (
        get(this.settings, 'share_white_list', '').indexOf(
          this.userInfo.userid
        ) > -1
      );
    },

    copyText() {
      return `我正在阅读《${
        this.bookInfo.name
      }》，点击下面链接来和我一起阅读吧~\n${getBookShareUrl(
        this.bookInfo.id,
        this.shareCode,
        this.autoSecretCode
      )}`;
    },

    posterUrl() {
      return `/api/front/poster/book?id=${this.bookInfo.id}`;
    },

    background() {
      return this.bookInfo && this.bookInfo.imgUrl
        ? `url(${this.bookInfo.imgUrl})`
        : 'transparent';
    },

    status() {
      let status = '更新中';
      if (this.bookInfo.status) {
        return this.bookInfo.status === '已完结'
          ? '已完结'
          : `最新章节-第${this.bookInfo.newestChapter}章`;
      }
      return status;
    },

    price() {
      let priceStr = '';
      const { goodInfo = {} } = this.bookInfo;
      if (goodInfo.type === 'free') {
        priceStr = '全书免费';
      } else if (goodInfo.type === 'normal') {
        priceStr = `每章需要 ${goodInfo.prise} 书币`;
      } else if (goodInfo.type === 'limit_chapter') {
        priceStr = `前 ${goodInfo.limit_chapter} 章免费，后续章节每章 ${goodInfo.prise} 书币`;
      } else if (goodInfo.type === 'limit_date') {
        priceStr = `${formatDateToNormalStr(
          new Date(goodInfo.limit_start_date)
        )} 至 ${formatDateToNormalStr(
          new Date(goodInfo.limit_end_date)
        )} 免费，后续章节每章 ${goodInfo.prise} 书币`;
      } else {
        priceStr = '全书免费';
      }
      return priceStr;
    },

    updateTime() {
      return formatDateToNormalStr(
        new Date(this.bookInfo.updateTime || Date.now() - 4 * 60 * 60 * 1000)
      );
    },
  },

  methods: {
    getButtonText(name) {
      return BUTTONS[name] ? BUTTONS[name].text : '';
    },

    getButtonIcon(name) {
      return BUTTONS[name] ? BUTTONS[name].icon : '';
    },

    handleButtonClick(name) {
      if (typeof this[BUTTONS[name].func] === 'function')
        this[BUTTONS[name].func]();
    },

    handleReadNow() {
      const gotoReader = () => {
        uni.navigateTo({
          url: `/pages/reader/index?book=${this.bookInfo.id}`,
        });
      };
      // 静默添加到阅读记录
      if (this.hasLogin) {
        if (!this.bookInfo.isInList && !this.hasAddToList) {
          this.$http({
            method: 'POST',
            url: '/api/front/booklist/add',
            data: { id: this.bookInfo.id },
            needAuth: true,
            skipToast: true,
          })
            .then((res) => {
              if (res.ok) this.hasAddToList = true;
              gotoReader();
            })
            .catch((err) => {
              gotoReader();
            });
        } else {
          gotoReader();
        }
      } else {
        const localReadRecords = uni.getStorageSync('readRecords') || [];
        const isInList = localReadRecords.some(
          (item) => item.id === this.bookInfo.id
        );
        if (!isInList) {
          localReadRecords.unshift(this.bookInfo);
          uni.setStorageSync('readRecords', localReadRecords);
        }
        gotoReader();
      }
    },

    handleShareBook() {
      if (this.hasLogin && this.isInWhiteList) {
        uni.showModal({
          title: '温馨提示',
          content:
            '点击“秘钥分享”将携带秘钥，用户打开此分享链接会自动解锁该书籍',
          showCancel: true,
          cancelText: '普通分享',
          confirmText: '秘钥分享',
          success: (res) => {
            if (res.confirm) {
              this.getPreCheckSecret().then((secret) => {
                this.$store.commit('updateAutoSecret', secret);
                this.$store.commit('updateShare', true);
              });
            } else {
              this.$store.commit('updateAutoSecret', '');
              this.$store.commit('updateShare', true);
            }
          },
        });
      } else {
        this.$store.commit('updateShare', true);
      }
    },

    handleShareClose() {
      this.$store.commit('updateShare', false);
    },

    handleBackToIndex() {
      let pages = getCurrentPages(); //当前页面
      let prevPage = pages[pages.length - 2]; //上一页面
      if (
        prevPage &&
        prevPage.$page &&
        prevPage.$page.route === '/pages/index/index'
      ) {
        wx.navigateBack();
      } else {
        wx.switchTab({
          url: '/pages/index/index',
        });
      }
    },

    // 获取自动解锁分享秘钥
    getPreCheckSecret() {
      return new Promise((resolve, reject) => {
        this.$http({
          method: 'POST',
          url: '/api/front/secret/pre_create',
          data: { bookid: this.bookInfo.id },
          needAuth: true,
          skipToast: false,
        }).then((res) => {
          if (res.ok) {
            resolve(res.data);
          }
        });
      });
    },
  },
};
</script>

<style lang="scss">
.header {
  min-height: 434rpx;
  overflow: hidden;
  position: relative;

  &__bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
    height: 110%;
    width: 110%;
    margin-top: -28rpx;
    margin-left: -28rpx;
    background-position: center center !important;
    background-size: 100% !important;
    filter: blur(28rpx) brightness(60%);
  }

  &__content {
    position: relative;
    z-index: 1;
    display: flex;
    flex-flow: column nowrap;
    width: 100%;
    height: 100%;
    padding: 40rpx 30rpx 30rpx;
    box-sizing: border-box;

    &-wrap {
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-start;
      align-items: flex-start;
      flex: 1;
    }

    &-img {
      width: 210rpx;
      margin-right: 30rpx;
      flex: none;
    }
    &-image {
      width: 210rpx;
      max-height: 290rpx;
    }

    &-detail {
      flex: 1;
      color: #ffffff;
      font-size: 28rpx;
      flex-flow: column nowrap;
    }

    &-title {
      font-size: 32rpx;
      color: #fff;
      margin-bottom: 15rpx;
      font-weight: bold;
    }

    &-des {
      font-size: 26rpx;
    }
  }

  &__buttons {
    flex: 1;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    margin-top: 40rpx;

    &-item {
      display: inline-block;
      text-align: center;
      background: rgba(255, 255, 255, 0.2);
      color: #fff;
      border-radius: 8rpx;
      height: 72rpx;
      line-height: 72rpx;
      margin: 0;
      padding: 0;
      font-size: 28rpx;
      margin-right: 40rpx;
      min-width: 192rpx;

      &:active {
        background: rgba(255, 255, 255, 0.4);
      }

      &:last-child {
        margin-right: 0;
      }
    }

    .iconfont {
      font-size: 28rpx;
      margin-right: 4rpx;
    }
  }
}
</style>
